package cn.com.dpc.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
	private static final long serialVersionUID = 2563876672373748748L;
	private ClientReceiveThread thread = null;
	private String host = "";
	private String userNo = "";
	private boolean connState = false;
	private static final String SUCCESS = MessageType.CLIENT_CONN_STATE
			+ "#success";
	private static final String FAIL = MessageType.CLIENT_CONN_STATE + "#fail";
	private static final int MAX_CONFIRM_ALARM_LENGTH = 30;
	// 告警过滤最大数量，不能重复
	public static final int MAX_COUNT = Integer.MAX_VALUE / 2;
	// 为了防止告警序列号重复，特加入此集合作为判断
	private Set<String> filter = new HashSet<String>();
	// 请求的站信息
	private String statNo = "0";
	private String devNo = "0";

	public void init() {
		host = "218.249.218.105";
		thread = new ClientReceiveThread(host, this);
		try {
			thread.openConnect();
		} catch (Exception e) {
			System.out.println("open connect error:");
		}
		connState = thread.isConnState();

		if (connState) {
			this.receive(SUCCESS);
		} else {
			this.receive(FAIL);
		}
		// 安全守护线程
//		Thread safe = new Thread(new Safe(this));
//		safe.start();
	}

	public void send(String msg) {
		System.out.println("send msg:" + msg);
		// 为了加入工号，不得不解析发下来的消息
		String[] tmpMsg = msg.split("#");
		String type = tmpMsg[0];

		if (tmpMsg[0].equals(String.valueOf(MessageType.USER_NO))) {
			userNo = tmpMsg[1];
		} else if (type.equals(String
				.valueOf(MessageType.REQUEST_RECOVER_CONFIRM_ALARM))
				|| type.equals(String
						.valueOf(MessageType.QEQUEST_CONFRIM_ALARM))) {
			// 通道包过大的时候自动给截取
			List<String> msgList = this.analy(msg);
			System.out.println(msgList.size() + "sss");
			for (String s : msgList) {
				thread.sendMsg(s);
			}
			return;
		} else if (type.equals(String.valueOf(MessageType.REQUEST_REAL_DATA))) {
			statNo = tmpMsg[1];
			devNo = tmpMsg[2];
		}
		if (thread.isConnState()) {
			thread.sendMsg(msg);
		}
	}

	//
	private List<String> analy(String msg) {

		String[] tmpMsg = msg.split("#");
		String userNo = tmpMsg[2];
		String[] alarmNos = tmpMsg[1].split(",");
		int count = 0;
		if (alarmNos.length % MAX_CONFIRM_ALARM_LENGTH == 0) {
			count = alarmNos.length / MAX_CONFIRM_ALARM_LENGTH;
		} else {
			count = alarmNos.length / MAX_CONFIRM_ALARM_LENGTH + 1;
		}
		List<String> msgList = new ArrayList<String>();
		StringBuffer alarmNoBuffer = new StringBuffer();
		if (alarmNos.length > MAX_CONFIRM_ALARM_LENGTH) {
			for (int i = 0; i < count; i++) {
				StringBuffer buffer = new StringBuffer();
				buffer.append(tmpMsg[0]).append("#");
				for (int j = i * MAX_CONFIRM_ALARM_LENGTH; j < (i + 1)
						* MAX_CONFIRM_ALARM_LENGTH
						&& j < alarmNos.length; j++) {
					alarmNoBuffer.append(alarmNos[j]);
					alarmNoBuffer.append(",");
				}
				if (alarmNoBuffer.length() > 0) {
					buffer.append(alarmNoBuffer.substring(0,
							alarmNoBuffer.length() - 1));
					buffer.append("#").append(userNo);
					msgList.add(buffer.toString());
				}
				alarmNoBuffer.delete(0, alarmNoBuffer.length());
			}
		} else {
			msgList.add(msg);
		}
		return msgList;
	}

	/**
	 * 收到消息有时候消息发生粘滞，暂时做一个特殊处理以#end结束
	 * 
	 * @param msg
	 */
	public void receive(String msg) {
		String[] tmpMsg = msg.split("#");
		// 有时候网络延迟可能会收到重复的告警信息，为了避免重复
		// 暂时通过一个队列里面放告警和恢复的告警信息5#SeqNum 6#SeqNum
		System.out.println("receive msg:" + msg);
		int msgIntHead = Integer.valueOf(tmpMsg[0]);
		if (msgIntHead == MessageType.REAL_ALARM
				|| msgIntHead == MessageType.RECOVER_ALARM) {
			String key = tmpMsg[0] + "#" + tmpMsg[1];
			if (filter.size() > MAX_COUNT)
				filter.clear();
			if (filter.contains(key)) {
				return;
			} else {
				filter.add(key);
			}
		} else if (msgIntHead == MessageType.RECEIVE_REAL_DATA) {
			System.out.println("statNo>>>>>>" + statNo + "---" + tmpMsg[1]);
			if (!statNo.equals(tmpMsg[1]))
				return;
		}
	}

	private class Safe implements Runnable {

		private Main Main;

		private Safe(Main Main) {
			this.Main = Main;
		}

		public void run() {
			while (true) {
				try {
					// 安全进程负责检测状态，当服务器程序退出的时候，发现客户端检测不到异常，只有通过发送
					// 过一段时间发送消息，发送的时候会抛出异常，暂时根据此模式来检测出现异常情况，重连
					if (thread.isConnState()) {
						thread.sendMsg("");
						System.out.println("send hearbeat message normal...");
					} else {
						thread = new ClientReceiveThread(host, Main);
						thread.openConnect();
						if (thread.isConnState()) {
							String msg = MessageType.REPLY_ALARM_FROM_DATABASE
									+ "#" + userNo;
							thread.sendMsg(String.valueOf(msg));
							String userNoMsg = MessageType.USER_NO + "#"
									+ userNo;
							thread.sendMsg(userNoMsg);
							Thread.sleep(1000);
							thread.sendMsg(String
									.valueOf(MessageType.REQUEST_ICON_MESSAGE));
							// 重新连接上后发送一次请求本站实时数据的信息，防止
							// SSManager重启后丢失定时发送的站信息
							String requestStatMsg = MessageType.REQUEST_REAL_DATA
									+ "#" + statNo + "#" + devNo;
							System.out
									.println("repeat connection send request station msg:");
							System.out.println(requestStatMsg);
							thread.sendMsg(requestStatMsg);
						}
					}
					// 判断和原来状态是否一样，如果一样就不发送给客户端发送连接状态消息
					// 如果不一样就发送连接状态消息
					if (thread.isConnState() != connState) {
						connState = thread.isConnState();
						if (thread.isConnState()) {
							Main.receive(SUCCESS);
						} else {
							Main.receive(FAIL);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				try {
					// 10s钟检测一下心跳信息
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					System.out.println("线程中断异常关闭原来连接");
					thread.inputClosed();
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Main Main = new Main();
		Main.init();

	}

	// private class Send implements Runnable{
	//
	// public void run() {
	// while(true){
	// if(msgQueue.isEmpty()){
	// lock.lock();
	// try{
	// try {
	// msgArrived.await();
	// } catch (InterruptedException e) {
	// e.printStackTrace();
	// }
	// }finally{
	// lock.unlock();
	// }
	// }else{
	// String msg = msgQueue.poll();
	// try {
	// winmain.eval((new StringBuilder("pushdata(\"")).append(msg).append(
	// "\")").toString());
	// } catch (Exception e1) {
	// e1.printStackTrace();
	// }
	// }
	// try {
	// Thread.sleep(100);
	// } catch (InterruptedException e) {
	// e.printStackTrace();
	// }
	// }
	// }
	//
	// }

}
